package com.bsb.biz.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.bsb.base.common.config.Const;
import com.bsb.base.common.util.CCORFile;
import com.bsb.base.common.util.ChangeAudioFormat;
import com.bsb.base.common.util.ChangeAudioListener;
import com.bsb.base.common.util.FileUtil;
import com.bsb.base.common.util.PicUtil;
import com.bsb.base.common.util.ShortUuid;
import com.bsb.base.common.util.SmsUtil;
import com.bsb.base.common.util.StringUtils;
import com.bsb.base.model.BsbUser;
import com.bsb.biz.service.BsbUserService;

import it.sauronsoftware.jave.EncoderException;

@Controller
public class IndexController {
	@Resource
	private BsbUserService bsbUserService;

	@Resource
	private ThreadPoolTaskExecutor taskExecutor;

	private static final Logger logger = Logger.getLogger(IndexController.class);

	@RequestMapping(value = { "/", "index" })
	public String index() {
		return "login";
	}

	@RequestMapping("/getPic/{imgName:.+}")
	public void getPhoto(@PathVariable(value = "imgName") String imgName, HttpServletResponse response,
			HttpServletRequest request) {
		if (StringUtils.isEmpty(imgName)) {
			return;
		}
		int indexOf = imgName.indexOf("_");
		if (indexOf < 0) {
			return;
		}
		int indexOf2 = imgName.indexOf(".");
		String substring;
		if(indexOf2>0){
			substring = imgName.substring(indexOf + 1,indexOf2);
		}else{
			substring = imgName.substring(indexOf + 1);
		}
		String imgPath = PicUtil.getPicUploadPath();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		long lt = new Long(substring);
		Date date = new Date(lt);
		String res = simpleDateFormat.format(date);

		String imagePath = imgPath + res;
		PicUtil.getPhoto(imgName, imagePath, response);
	}

	/**
	 * 上传图片
	 * 
	 * @param file
	 * @param type
	 * @param request
	 */
	@RequestMapping("/uploadimage")
	@ResponseBody
	public String uploadimage(HttpServletRequest request,MultipartFile file) {
		File upFile = FileUtil.multipartToFile(file);
		String uuid = ShortUuid.generateShortUuid();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		long currentTimeMillis = System.currentTimeMillis();
		String fileName = uuid + "_" + currentTimeMillis;
		Date date = new Date(currentTimeMillis);
		String res = simpleDateFormat.format(date);
		String destDirName = PicUtil.getPicUploadPath() + res;
		CCORFile.createDir(destDirName);
		FileUtil.upFile(upFile, fileName, destDirName);
		return fileName;
	}

	/**
	 * 上传语音
	 * 
	 * @param file
	 * @param type
	 * @param request
	 */
	@RequestMapping("/uploadaudio")
	@ResponseBody
	public Object uploadvoice(MultipartFile file,
			@RequestParam(value = "userid", required = true) String phone,
			@RequestParam(value = "duration", required = false) Integer duration,
			HttpServletRequest request) {
		File upFile = FileUtil.multipartToFile(file);
		String originalFilename = file.getOriginalFilename();
		String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
		String uuid = ShortUuid.generateShortUuid();
		String fileName = uuid + "_" + phone + suffix;
		String destDirName = PicUtil.getVoiceUploadPath() + phone;
		Map<String, Object> map = new HashMap<String, Object>();
		FileUtil.upFile(upFile, fileName, destDirName);
		//转换为aac
/*		ChangeAudioListener listener = new ChangeAudioListener();
		taskExecutor.execute(new Runnable() {

			@Override
			public void run() {
				try {
					ChangeAudioFormat.changeToAac(upFile, destDirName, fileName, listener);
				} catch (EncoderException e) {
					e.printStackTrace();
				}
			}
		});*/
		try {

			map.put("fileName", fileName);
			map.put("duration", duration);
			// map.put("duration", listener.getMediaInfo().getDuration());
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@RequestMapping("/getVoice/{name:.+}")
	public void getVoice(@PathVariable(value = "name") String name, HttpServletResponse response,
			HttpServletRequest request) {
		if (StringUtils.isEmpty(name)) {
			return;
		}
		String fileName = System.currentTimeMillis() + name;
		int indexOf = name.indexOf("_");
		int indexOf2 = name.indexOf(".");
		if (indexOf < 0 || indexOf2 < 0) {
			logger.info(name + "==文件名字格式错误");
			return;
		}
		int length = name.length();
		String substring = name.substring(indexOf + 1, length - 4);
		name = Const.getVoiceBasePath() + substring + "/" + name;
		try {
			FileUtil.downloadAudio(request, response, name, fileName);
		} catch (Exception e) {
			logger.error("读取音频文件流异常"+e.getMessage());
		}
		
	}

	@RequestMapping("/sendSms/{phone}")
	@ResponseBody
	public Object sendSms(@PathVariable(value = "phone") String phone) {
		String msg = "";
		if (!StringUtils.isMobile(phone)) {
			msg = "手机号码格式不正确";
			return msg;
		}
		BsbUser userByPhone = bsbUserService.getUserByPhone(phone);
		if (null != userByPhone) {
			msg = "该手机号已存在";
			return msg;
		}
		String code = SmsUtil.getCode();
		String[] str = new String[] { code, "5" };
		try {
			String sendSms = SmsUtil.sendSms("8a216da8592b16a1015938d4129f03f0", "148766", phone, str);
			if (StringUtils.isEmpty(sendSms)) {
				msg = "发送短信时出现错误，请联系管理员";
				return msg;
			}
			Session session = SecurityUtils.getSubject().getSession(false);
			if (null != session) {
				session.setAttribute("smscode", code);
				// TimerTask实现5分钟后从session中删除checkCode
				final Timer timer = new Timer();
				timer.schedule(new TimerTask() {
					@Override
					public void run() {
						session.removeAttribute("smscode");
						logger.info("smscode删除成功" + code);
						timer.cancel();
					}
				}, 5 * 60 * 1000);
			}
		} catch (InvalidSessionException e) {
			e.printStackTrace();
			msg = "系统繁忙，请联系管理员";
			return msg;
		}
		return true;
	}

	@RequestMapping("/checkPhoneExist")
	@ResponseBody
	public Object checkPhoneExist(@RequestParam(value = "phone", required = true) String phone) {
		if (!StringUtils.isMobile(phone)) {
			return false;
		}
		BsbUser userByPhone = bsbUserService.getUserByPhone(phone);
		if (null == userByPhone) {
			return true;
		}
		return false;
	}

}
